package com.atguigu.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.constant.ProductConstant;
import com.atguigu.common.to.SkuReductionTo;
import com.atguigu.common.to.SpuBoundTo;
import com.atguigu.common.to.es.SkuEsModel;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.product.entity.*;
import com.atguigu.gulimall.product.service.*;
import com.atguigu.gulimall.product.vo.*;
import com.atguigu.gulimall.product.feign.*;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.atguigu.common.utils.PageUtils;
import com.atguigu.common.utils.Query;
import com.atguigu.gulimall.product.dao.SpuInfoDao;
import org.springframework.transaction.annotation.Transactional;

@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SpuImagesService spuImagesService;

    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    AttrService attrService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    ConponFeignService conponFeignService;

    @Autowired
    BrandService brandService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    SearchFeignService searchFeignService;

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long id) {
        SkuInfoEntity skuInfoEntity = skuInfoService.getById(id);
        SpuInfoEntity spuInfo = this.baseMapper.selectById(skuInfoEntity.getSpuId());
        return spuInfo;
    }

    @Transactional
    @Override
    public void spuUp(Long spuId) throws IOException {

        // 1. 查询Sku基本信息
        List<SkuInfoEntity> skuInfoEntities = skuInfoService.list(new QueryWrapper<SkuInfoEntity>().eq("spu_id", spuId));
        // 查询attrs,关联的表: `pms_product_attr_value`
        // 每个sku的规格参数都是一样的,因此只需要查一遍就行并且需要筛选出可检索的规格参数
        List<ProductAttrValueEntity> productAttrValueEntities =
                productAttrValueService.list(new QueryWrapper<ProductAttrValueEntity>().eq("spu_id", spuId));
        List<Long> attrIds = productAttrValueEntities.stream().map(item -> {
            return item.getAttrId();
        }).collect(Collectors.toList());
        // 查询可检索的属性
        // 我理解attrIds这个属性是spu中的所有属性,但是在后台有些属性是可以搜的有些属性是可以检索有些是不能检索的
        // 判断是否能检索的方式就是看属性表里面有没有该属性,有就是可以检索,没有就是不能检索
        /**
        List<Long> ids = attrIds.stream().map(attrId -> {
            AttrEntity attrEntity = attrService.getById(attrId);
            if (attrEntity != null) {
                return attrEntity.getAttrId();
            }
            return null;
        }).collect(Collectors.toList());
         */
        // 提前查询每个skuId对应的库存,到时候封装到Es类中
        List<Long> skuIds = skuInfoEntities.stream().map(item -> {
            return item.getSkuId();
        }).collect(Collectors.toList());

        Map<Long, Boolean> stockMap = null;

        try{
            R r = wareFeignService.queryStock(skuIds);
            TypeReference<List<SkuStockVo>> typeReference = new TypeReference<List<SkuStockVo>>() {
            };
            System.out.println("datashi1:" + typeReference);
            for (SkuStockVo datum : r.getData(typeReference)) {
                System.out.println(datum);
            }
            stockMap = r.getData(typeReference).stream().collect(Collectors.toMap(SkuStockVo::getSkuId, SkuStockVo::getHasStock));
            System.out.println(stockMap);
            System.out.println("emd");
        } catch (Exception e){
            log.error("远程调用ware服务出现错误{}"+e);
        }

        List<Long> ids = attrService.querySearchTypeAttr(attrIds);
        // 属性id去重
        Set<Long> set = new HashSet<>(ids);
        // 根据去重属性id查询出属性信息并封装到返回EsSku类中
        List<SkuEsModel.Attrs> attrsList = productAttrValueEntities.stream().filter(item -> {
            return set.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs);
            return attrs;
        }).collect(Collectors.toList());

        // 将sku属性封装到EsSku类中
        Map<Long, Boolean> finalStockMap = stockMap;

        List<SkuEsModel> skuEsModelList = skuInfoEntities.stream().map(item -> {

            SkuEsModel skuEsModel = new SkuEsModel();
            // 属性对拷
            BeanUtils.copyProperties(item, skuEsModel);
            // skuPrice，skuImg 不能对拷属性,需要自己设置
            skuEsModel.setSkuPrice(item.getPrice());
            skuEsModel.setSkuImg(item.getSkuDefaultImg());
            // TODO hasStock，库存信息需要通过 openfeign去调用查询
            if (finalStockMap == null) {
                skuEsModel.setHasStock(true);
            } else {
                skuEsModel.setHasStock(finalStockMap.get(item.getSkuId()));
            }
            // TODO hotScore 涉及复杂的操作,因此,将新上架的商品的热度设置为0
            skuEsModel.setHotScore(0L);
            // 查出brandName,brandImg
            BrandEntity brandEntity = brandService.getById(item.getBrandId());
            skuEsModel.setBrandImg(brandEntity.getLogo());
            skuEsModel.setBrandName(brandEntity.getName());
            // 查出catelogName
            CategoryEntity categoryEntity = categoryService.getById(item.getCatalogId());
            skuEsModel.setCatalogName(categoryEntity.getName());
            // 每个sku的规格参数都是一样的,因此,只需要查一遍就行并且需要筛选出可检索的规格参数
        skuEsModel.setAttrs(attrsList);
        return skuEsModel;
    }).collect(Collectors.toList());

    // 远程调用ES保存信息
    R r = searchFeignService.ProductSave(skuEsModelList);
        if(r.getCode() == 0){
            // 成功的话要修改SPU的发布状态
            SpuInfoEntity spuInfoEntity = this.baseMapper.selectOne(new QueryWrapper<SpuInfoEntity>().eq("id", spuId));
            spuInfoEntity.setPublishStatus(ProductConstant.PublishStatusConstant.UP_TYPE.getCode());
            spuInfoEntity.setUpdateTime(new Date());
            this.updateById(spuInfoEntity);
        }else{
            // TODO 远程调用失败. 出现问题:重复调用,专业术语:接口幂等性:重试机制?xxx
        }

    }



    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        System.out.println("方法执行到这了！！！");
        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();

        String key = (String)params.get("key");
        if(!StringUtils.isEmpty(key)){
            queryWrapper.and(w->{
                w.eq("id",key).or().like("spu_name",key);
            });
        }

        String catelogId = (String)params.get("catalogId");
        if (!StringUtils.isEmpty(catelogId)  && !"0".equalsIgnoreCase(catelogId)){
            queryWrapper.eq("catalog_id",catelogId);
        }

        String brandId = (String)params.get("brandId");
        if(!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)){
            queryWrapper.eq("brand_id",brandId);
        }

        String status = (String)params.get("status");
        if(!StringUtils.isEmpty(status)){
            queryWrapper.eq("publish_status",status);
        }

        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                queryWrapper
        );
        return new PageUtils(page);
    }

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        //1. 保存spu基本信息 `pms_spu_info`
        SpuInfoEntity infoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo,infoEntity);
        infoEntity.setCreateTime(new Date());
        infoEntity.setUpdateTime(new Date());
        this.save(infoEntity);

        //2. 保存spu的描述图片 `pms_spu_info_desc`
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity descEntity = new SpuInfoDescEntity();
        descEntity.setSpuId(infoEntity.getId());
        // 保存的是多个图片地址,之间用逗号进行分隔
        descEntity.setDecript(String.join(",",decript));
        spuInfoDescService.save(descEntity);

        //3. 保存spu的图片集`pms_spu_images`
        List<String> images = vo.getImages();

        if(images != null && images.size() != 0){
            List<SpuImagesEntity> collect = images.stream().map(image -> {
                SpuImagesEntity imagesEntity = new SpuImagesEntity();
                imagesEntity.setSpuId(infoEntity.getId());
                imagesEntity.setImgUrl(image);
                return imagesEntity;
            }).collect(Collectors.toList());
            spuImagesService.saveBatch(collect);
        }

        // 4.保存spu的规则参数 `pms_product_attr_value`
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {

            ProductAttrValueEntity productAttrValueEntity = new ProductAttrValueEntity();
            productAttrValueEntity.setSpuId(infoEntity.getId());
            productAttrValueEntity.setAttrId(attr.getAttrId());
            AttrEntity byId = attrService.getById(attr.getAttrId());
            productAttrValueEntity.setAttrName(byId.getAttrName());
            productAttrValueEntity.setAttrValue(attr.getAttrValues());
            productAttrValueEntity.setQuickShow(attr.getShowDesc());
            return productAttrValueEntity;

        }).collect(Collectors.toList());
        productAttrValueService.saveBatch(collect);

        //5. 保存spu的积分信息 `gulimall_sms` -> `sms_spu_bouds`
        Bounds bounds = vo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        spuBoundTo.setBuyBounds(bounds.getBuyBounds());
        spuBoundTo.setGrowBounds(bounds.getGrowBounds());
        spuBoundTo.setSpuId(infoEntity.getId());
        R r = conponFeignService.saveSpuBounds(spuBoundTo);

        if(r.getCode()!=0){
            log.error("远程保存spu积分信息失败");
        }

        //6. 保存spu对应的所有sku信息
        List<Skus> skus = vo.getSkus();
        if(skus != null && skus.size() > 0){
            skus.forEach(item -> {
                String defaultImg = "";
                // 查找出默认图片
                for (Images image : item.getImages()) {
                    if(image.getDefaultImg() == 1){
                        defaultImg = image.getImgUrl();
                    }
                }

                SkuInfoEntity skuInfo = new SkuInfoEntity();

                BeanUtils.copyProperties(item,skuInfo);
                skuInfo.setSpuId(infoEntity.getId());
                skuInfo.setBrandId(infoEntity.getBrandId());
                skuInfo.setCatalogId(infoEntity.getCatalogId());
                skuInfo.setSaleCount(0L);
                skuInfo.setSkuDefaultImg(defaultImg);
                //6.1 保存sku的基本信息`pms_sku_info`
                skuInfoService.save(skuInfo);

                //6.2 sku的图片信息`pms_sku_images`
                Long skuId = skuInfo.getSkuId();

                List<SkuImagesEntity> collect1 = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(collect1);

                //6.3 sku的销售属性信息 `pms_sku_sale_attr_value`
                List<Attr> attrs = item.getAttr();
                List<SkuSaleAttrValueEntity> collect2 = attrs.stream().map(attr -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(attr,skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(collect2);

                //6.4 sku的优惠,满减等信息 `gulimall_sms` > `sms_sku_ladder``/`sms_sku_full_reduction`/`sms_member_price`
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item,skuReductionTo);
                skuReductionTo.setSkuId(infoEntity.getId());

                //因为该方法是既有保存满量打折又有保存满减优惠的方法,所以就判断
                //如果满减和满量的标准都大于0,即该sku下面设置了有满减和满量,那么就执行该方法
                if(skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1)
                {
                    R r1 = conponFeignService.saveSkuReduction(skuReductionTo);
                    if (r.getCode() != 0) {
                        log.error("远程保存spu优惠信息失败");
                    }
                }
            });
        }
    }
}
























